package com.gjl.app.oauth.params;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.gjl.app.oauth.common.OauthConstants;
import com.gjl.app.oauth.common.OauthUtil;

public class OauthParam {
	
	private static final String PARAM_SEPARATOR = "%26";
	
	private List<KeyValuePair> params;
	
	public OauthParam(){
		params = new ArrayList<KeyValuePair>();
		params.add(new KeyValuePair(OauthConstants.VERSION, "1.0"));
		params.add(new KeyValuePair(OauthConstants.TIMESTAMP, OauthUtil.generateTs()));
		params.add(new KeyValuePair(OauthConstants.CONSUMER_KEY, OauthConstants.HMAC_SHA1));
	}
	
	public List<KeyValuePair> getParams() {
		return params;
	}

	public void setParams(List<KeyValuePair> params) {
		this.params = params;
	}
	
	public void put(String key, String value) {
		KeyValuePair kvp = new KeyValuePair(key, value);
		params.add(kvp);
	}
	
	public void put(KeyValuePair kvp) {
		params.add(kvp);
	}
	
	public KeyValuePair get(int i) {
		return params.get(i);
	}
	
	public KeyValuePair getKeyValuePairByKey(String key){
		KeyValuePair kvp = null;
		for(KeyValuePair each : params) {
			if (each.getKey().equals(key)) {
				kvp = each;
				break;
			}
		}
		return kvp;
	}
	
	@Override
	public String toString() {
		Collections.sort(params);
		StringBuffer buffer = new StringBuffer();
		for(int i = 0; i < params.size(); i++) {
			if (i < params.size() - 1) {
				buffer.append(params.get(i)).append(PARAM_SEPARATOR);
			} else {
				buffer.append(params.get(i));
			}
		}
		return buffer.toString();
	}
	
}
